// 今日推荐组件 - 无缝衔接轮播
let todayRecommend = {
  template: `
  <div class="show">
    <div class="py-container">
      <div class="yui3-g Recommend">
        <div class="yui3-u-1-6 clock">
          <div class="time">
            <img src="../img/clock.png"/>
            <h3>今日推荐</h3>
          </div>
        </div>
        <div class="yui3-u-5-6 recommend-carousel">
          <div class="carousel-container" @mouseenter="pauseCarousel" @mouseleave="startCarousel">
            <div 
              class="carousel-wrapper" 
              :style="{ transform: 'translateX(' + translateX + 'px)', transition: transitionDuration }"
              @transitionend="handleTransitionEnd"
            >
              <div class="carousel-item" v-for="(item, index) in displayItems" :key="'item-' + index">
                <a @click="toItemDetail(item.id)" target="_blank">
                  <img :src="item.image" :alt="item.title"/>
                </a>
              </div>
            </div>
<!--            &lt;!&ndash; 轮播指示器 &ndash;&gt;-->
<!--            <div class="carousel-indicators" v-if="recommendItems.length > 0">-->
<!--              <span -->
<!--                v-for="(item, index) in recommendItems" -->
<!--                :key="'indicator-' + index" -->
<!--                :class="{ active: currentRealIndex === index }"-->
<!--                @click="goToSlide(index)"-->
<!--              ></span>-->
<!--            </div>-->
          </div>
        </div>
      </div>
    </div>
  </div>
  `,
  name: "todayRecommend",
  data() {
    return {
      recommendItems: [],
      currentIndex: 0, // 当前显示的索引（包含克隆项）
      currentRealIndex: 0, // 当前真实的索引（用于指示器）
      carouselInterval: null,
      translateX: 0,
      itemWidth: 0, // 每个item的实际像素宽度
      containerWidth: 0, // 容器宽度
      transitionDuration: 'transform 0.5s ease-in-out',
      isTransitioning: false // 防止过渡期间的重复操作
    }
  },
  computed: {
    // 用于显示的items，包含前后克隆项以实现无缝循环
    displayItems() {
      if (this.recommendItems.length === 0) return [];
      
      const items = [];
      const originalItems = this.recommendItems;
      
      // 前面添加最后5个项目的克隆（用于向左无缝切换）
      for (let i = 0; i < 5 && i < originalItems.length; i++) {
        console.log("轮播图运作中");
        items.push({
          ...originalItems[originalItems.length - 5 + i],
          isClone: true,
          cloneType: 'prev'
        });
      }
      
      // 添加所有原始项目
      originalItems.forEach(item => {
        items.push({ ...item, isClone: false });
      });
      
      // 后面添加前5个项目的克隆（用于向右无缝切换）
      for (let i = 0; i < 5 && i < originalItems.length; i++) {
        items.push({
          ...originalItems[i],
          isClone: true,
          cloneType: 'next'
        });
      }
      
      return items;
    },
    
    // 每次显示5个项目所需的总宽度
    visibleWidth() {
      return this.itemWidth * 5;
    }
  },
  mounted() {
    this.loadRecommendData();
    this.initializeCarousel();
    window.addEventListener('resize', this.handleResize);
  },
  beforeDestroy() {
    if (this.carouselInterval) {
      clearInterval(this.carouselInterval);
    }
    window.removeEventListener('resize', this.handleResize);
  },
  methods: {
    toItemDetail(id) {
      location.href = `/item-detail.html?id=${id}`;
    },
    
    loadRecommendData() {
      axios.get("/today-recommend")
        .then(resp => {
          if (resp && resp.length > 0) {
            this.recommendItems = resp;
          } else {
            this.recommendItems = [
              {id: 1, image: './img/today01.png', title: '今日推荐1'},
              {id: 2, image: './img/today02.png', title: '今日推荐2'},
              {id: 3, image: './img/today03.png', title: '今日推荐3'},
              {id: 4, image: './img/today04.png', title: '今日推荐4'},
              {id: 5, image: './img/today01.png', title: '今日推荐5'},
              {id: 6, image: './img/today02.png', title: '今日推荐6'},
              {id: 7, image: './img/today03.png', title: '今日推荐7'},
              {id: 8, image: './img/today04.png', title: '今日推荐8'}
            ];
          }
          this.$nextTick(() => {
            this.initializeCarousel();
          });
        })
        .catch(err => {
          console.log('获取今日推荐数据失败:', err);
          this.recommendItems = [
            {id: 1, image: './img/today01.png', title: '今日推荐1'},
            {id: 2, image: './img/today02.png', title: '今日推荐2'},
            {id: 3, image: './img/today03.png', title: '今日推荐3'},
            {id: 4, image: './img/today04.png', title: '今日推荐4'},
            {id: 5, image: './img/today01.png', title: '今日推荐5'},
            {id: 6, image: './img/today02.png', title: '今日推荐6'},
            {id: 7, image: './img/today03.png', title: '今日推荐7'},
            {id: 8, image: './img/today04.png', title: '今日推荐8'}
          ];
          this.$nextTick(() => {
            this.initializeCarousel();
          });
        });
    },
    
    // 初始化轮播
    initializeCarousel() {
      if (this.recommendItems.length === 0) return;
      
      this.$nextTick(() => {
        this.calculateDimensions();
        // 设置初始位置到第一个真实项目
        this.currentIndex = 5; // 跳过前面的5个克隆项
        this.currentRealIndex = 0;
        this.updateTranslateX(false); // 不使用动画
        this.startCarousel();
      });
    },
    
    // 计算尺寸
    calculateDimensions() {
      const container = this.$el.querySelector('.carousel-container');
      if (container) {
        this.containerWidth = container.offsetWidth;
        this.itemWidth = this.containerWidth / 5; // 每次显示5个项目
      }
    },
    
    // 处理窗口大小变化
    handleResize() {
      this.calculateDimensions();
      this.updateTranslateX(false);
    },
    
    // 更新translateX值
    updateTranslateX(useTransition = true) {
      this.transitionDuration = useTransition ? 'transform 0.5s ease-in-out' : 'none';
      this.translateX = -this.currentIndex * this.itemWidth;
    },
    
    // 开始轮播
    startCarousel() {
      if (this.carouselInterval) {
        clearInterval(this.carouselInterval);
      }
      
      if (this.recommendItems.length <= 5) return; // 如果项目数量不足，不启动自动轮播
      
      this.carouselInterval = setInterval(() => {
        if (!this.isTransitioning) {
          this.nextSlide();
        }
      }, 1500);
    },
    
    // 暂停轮播
    pauseCarousel() {
      if (this.carouselInterval) {
        clearInterval(this.carouselInterval);
        this.carouselInterval = null;
      }
    },
    
    // 下一张
    nextSlide() {
      if (this.isTransitioning) return;
      
      this.isTransitioning = true;
      this.currentIndex++;
      this.updateTranslateX(true);
      
      // 更新真实索引
      this.currentRealIndex = (this.currentRealIndex + 1) % this.recommendItems.length;
    },
    
    // 上一张
    prevSlide() {
      if (this.isTransitioning) return;
      
      this.isTransitioning = true;
      this.currentIndex--;
      this.updateTranslateX(true);
      
      // 更新真实索引
      this.currentRealIndex = this.currentRealIndex === 0 
        ? this.recommendItems.length - 1 
        : this.currentRealIndex - 1;
    },
    
    // 跳转到指定slide
    goToSlide(realIndex) {
      if (this.isTransitioning) return;
      
      this.isTransitioning = true;
      this.currentRealIndex = realIndex;
      this.currentIndex = realIndex + 5; // 加上前面的克隆项数量
      this.updateTranslateX(true);
    },
    
    // 处理过渡结束
    handleTransitionEnd() {
      this.isTransitioning = false;
      
      // 检查是否需要无缝切换
      const cloneCount = 5;
      const totalRealItems = this.recommendItems.length;
      
      // 如果滚动到右侧克隆区域，跳转到对应的真实位置
      if (this.currentIndex >= cloneCount + totalRealItems) {
        const targetRealIndex = this.currentIndex - cloneCount - totalRealItems;
        this.currentIndex = cloneCount + targetRealIndex;
        this.updateTranslateX(false);
      }
      // 如果滚动到左侧克隆区域，跳转到对应的真实位置
      else if (this.currentIndex < cloneCount) {
        const targetRealIndex = this.currentIndex + totalRealItems;
        this.currentIndex = cloneCount + targetRealIndex - cloneCount;
        this.updateTranslateX(false);
      }
    }
  }
};

// 猜你喜欢组件保持不变
let guessYouLike = {
  template: `
  <div class="like">
    <div class="py-container">
      <div class="title">
        <h3 class="fl">猜你喜欢</h3>
        <b class="border"></b>
        <a href="javascript:;" class="fr tip changeBnt" @click="loadLikeData"><i></i>换一换</a>
      </div>
      <div class="bd">
        <ul class="clearfix yui3-g Favourate picLB" id="picLBxxl">
          <li class="yui3-u-1-6" v-for="(group, groupIndex) in groupedItems" :key="groupIndex">
            <dl class="picDl" :class="groupClass(groupIndex)">
              <dd style="margin-left: 0;" v-for="(item, itemIndex) in group" :key="itemIndex">
                <a @click="toItemDetail(item.id)" class="pic"><img :src="item.image" :alt="item.title"/></a>
                <div class="like-text">
                  <p v-for="(desc, descIndex) in item.descriptions" :key="descIndex">{{desc}}</p>
                  <h3>{{item.price}}</h3>
                </div>
              </dd>
            </dl>
          </li>
        </ul>
      </div>
    </div>
  </div>
  `,
  name: "guessYouLike",
  data() {
    return {
      likeItems: [],
      defaultItems: [
        {
          id: 1,
          image: './img/like_02.png',
          title: '阳光美包新款单肩包女包时尚子母包四件套女',
          descriptions: ['阳光美包新款单肩包女包时尚子母包四件套女'],
          price: '¥116.00'
        },
        {
          id: 2,
          image: './img/like_01.png',
          title: '爱仕达 30CM炒锅不粘锅NWG8330E电磁炉炒',
          descriptions: ['爱仕达 30CM炒锅不粘锅NWG8330E电磁炉炒'],
          price: '¥116.00'
        },
        {
          id: 3,
          image: './img/like_03.png',
          title: '爱仕达 30CM炒锅不粘锅NWG8330E电磁炉炒',
          descriptions: ['爱仕达 30CM炒锅不粘锅NWG8330E电磁炉炒'],
          price: '¥116.00'
        },
        {
          id: 4,
          image: './img/like_02.png',
          title: '阳光美包新款单肩包女包时尚子母包四件套女',
          descriptions: ['阳光美包新款单肩包女包时尚子母包四件套女'],
          price: '¥116.00'
        },
        {
          id: 5,
          image: './img/like_01.png',
          title: '捷波朗（jabra）BOOSI劲步',
          descriptions: ['捷波朗（jabra）BOOSI劲步'],
          price: '¥236.00'
        },
        {
          id: 6,
          image: './img/like_02.png',
          title: '三星（G5500）移动联通双网通',
          descriptions: ['三星（G5500）', '移动联通双网通'],
          price: '¥566.00'
        },
        {
          id: 7,
          image: './img/like_03.png',
          title: '美的（Midea）电饭煲4L智能预约',
          descriptions: ['美的（Midea）电饭煲4L智能预约'],
          price: '¥199.00'
        },
        {
          id: 8,
          image: './img/like_01.png',
          title: '耐克 NIKE AIR MAX 男子运动鞋',
          descriptions: ['耐克 NIKE AIR MAX 男子运动鞋'],
          price: '¥699.00'
        },
        {
          id: 9,
          image: './img/like_02.png',
          title: 'Apple iPhone 12 64GB 黑色',
          descriptions: ['Apple iPhone 12 64GB 黑色'],
          price: '¥4599.00'
        },
        {
          id: 10,
          image: './img/like_03.png',
          title: '华为 HUAWEI MateBook X Pro',
          descriptions: ['华为 HUAWEI MateBook X Pro'],
          price: '¥8999.00'
        },
        {
          id: 11,
          image: './img/like_01.png',
          title: '苏泊尔（SUPOR）电压力锅 5L',
          descriptions: ['苏泊尔（SUPOR）电压力锅 5L'],
          price: '¥399.00'
        },
        {
          id: 12,
          image: './img/like_02.png',
          title: '小米（MI）空气净化器Pro H',
          descriptions: ['小米（MI）空气净化器Pro H'],
          price: '¥1299.00'
        }
      ]
    }
  },
  computed: {
    groupedItems() {
      const groups = [];
      for (let i = 0; i < this.likeItems.length; i += 2) {
        groups.push(this.likeItems.slice(i, i + 2));
      }
      return groups;
    }
  },
  mounted() {
    this.loadLikeData();
  },
  methods: {
    toItemDetail(id) {
      location.href = `/item-detail.html?id=${id}`;
    },
    loadLikeData() {
      axios.get("/guess-you-like")
        .then(resp => {
          if (resp && resp.length > 0) {
            this.likeItems = resp;
          } else {
            this.likeItems = this.defaultItems;
          }
        })
        .catch(err => {
          console.log('获取猜你喜欢数据失败:', err);
          this.likeItems = this.defaultItems;
        });
    },
    groupClass(index) {
      const classes = ['huozhe', 'jilu', 'tuhua', 'huozhe', 'jilu', 'tuhua'];
      return classes[index % classes.length];
    }
  }
};

// 注册组件
Vue.component("todayRecommend", todayRecommend);
Vue.component("guessYouLike", guessYouLike);